<template>
  <div class="platform-wrapper">
    <div class="home">
      <div class="top">
        <div class="title-wrapper">
          <div class="title">首页设置</div>
        </div>
        <el-button type="primary" size="small" @click="homeSetting">确认</el-button>
      </div>
      <div class="content">
        <!-- <div class="video-module d-flex">
          <div class="d-flex">
            <p>是否显示视频模块</p>
            <el-switch v-model="showVideo" style="margin-right: 30px" @change="videoSwitchChange" />
          </div>
          <div>
            <el-radio v-model="homeRadio" label="dynamic" :disabled="videoDisable">视频为首页</el-radio>
            <el-radio v-model="homeRadio" label="shop">商城为首页</el-radio>
          </div>
        </div> -->
        <div v-if="list.length" class="icon-wrapper show" style="margin-top: 30px">
          <el-form>
            <el-form-item label="底部导航icon上传：">
              <div>未选中状态:</div>
              <div class="inActive">
                <my-upload
                  v-for="item of list"
                  v-show="!(item.is_show === 0)"
                  :key="item.sort"
                  :width="50"
                  :height="50"
                  tip="建议尺寸50*50"
                  :title="item.name"
                  small="small"
                  :img="item.icon"
                  @click.native="setIndex(item)"
                  @success="unCheckedSuccess"
                  @remove="unCheckedRemove"
                />
              </div>
              <div style="margin-left: 138px; margin-top:10px">选中状态:</div>
              <div class="active">
                <my-upload
                  v-for="item of list"
                  v-show="!(item.is_show === 0)"
                  :key="item.sort"
                  :width="50"
                  :height="50"
                  tip="建议尺寸50*50"
                  :title="item.name"
                  small="small"
                  :img="item.icon_on"
                  @click.native="setIndex(item)"
                  @remove="checkedRemove"
                  @success="CheckedSuccess"
                />
              </div>
            </el-form-item>
            <el-form-item label="底部导航文字修改：">
              <div v-if="homeSettingParams.memu.length" class="name-wrapper d-flex">
                <div
                  v-for="(item, index) of homeSettingParams.memu"
                  :key="index"
                  class="name d-flex w-60"
                >
                  <p>{{ list[index].name }}：</p>
                  <el-input v-model="item.name" size="mini" />
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="goods">
      <div class="top">
        <div class="title-wrapper">
          <div class="title">商品设置</div>
        </div>
        <el-button type="primary" size="small" @click="goodsSettingSubmit">确认</el-button>
      </div>
      <div class="content d-flex">
        <div class="d-flex">
          <p>是否需要服务</p>
          <el-switch v-model="isNeedServe" style="margin-right: 30px" />
        </div>
        <div class="d-flex">
          <p>是否需要商品</p>
          <el-switch v-model="isNeedGoods" style="margin-right: 30px" />
        </div>
        <div>
          <el-radio v-model="GoodsRadio" label="byServe" :disabled="serveDisable">服务为主</el-radio>
          <el-radio
            v-model="GoodsRadio"
            :disabled="goodsDisable"
            label="byGoods"
          >商品为主</el-radio>
        </div>
      </div>
    </div>
    <div class="theme-color">
      <div class="top">
        <div class="title-wrapper">
          <div class="title">主体色设置</div>
        </div>
        <el-button type="primary" size="small" @click="colorSetting">确认</el-button>
      </div>
      <div class="content">
        <el-form class="d-flex">
          <el-form-item label="主题色" class="d-flex">
            <el-color-picker
              v-model="colorParams.theme_color"
              show-alpha
              :predefine="predefineColors"
            />
          </el-form-item>
          <el-form-item label="副主题色" class="d-flex">
            <el-color-picker
              v-model="colorParams.assistant_theme_color"
              show-alpha
              :predefine="predefineColors"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="basic-infor">
      <div class="top">
        <div class="title-wrapper">
          <div class="title">基本信息设置</div>
        </div>
        <el-button type="primary" size="small" @click="basicInfoSetting">确认</el-button>
      </div>
      <div class="content">
        <el-form ref="ruleForm" :model="basicInfoParams" :rules="rules">
          <el-form-item label="平台名称：" prop="name">
            <el-input
              v-model="basicInfoParams.name"
              size="medium"
              style="width: 300px"
              placeholder="请输入平台名称"
            />
          </el-form-item>
          <el-form-item label="上传logo：" class="d-flex-top">
            <my-upload
              :width="100"
              :height="100"
              class-name="big"
              :img="basicInfoParams.logo"
              medium="medium"
              @remove="logoRemove"
              @success="logoSuccess"
            />
          </el-form-item>
          <el-form-item label="登录页广告:">
            <el-upload
              action="https://wx.chengkenet.com/api/common/upload/"
              list-type="picture-card"
              :file-list="fileList"
              :on-preview="handlePictureCardPreview"
              :on-success="handleAdSuccess"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt>
            </el-dialog>
          </el-form-item>
          <el-form-item label="联系电话：" prop="service_tel">
            <el-input
              v-model="basicInfoParams.service_tel"
              size="medium"
              style="width: 300px"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import MyUpload from '@/views/add-editor/component/my-upload'
import { setPlatform, getPlatform } from '@/api/platform-setting'
import { mapMutations } from 'vuex'
const ERR_OK = 200

export default {
  components: {
    MyUpload
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      const isEffect = /^1[3456789]\d{9}$/
      if (!isEffect.test(value)) {
        callback(new Error('请填写有效手机号码！'))
      } else {
        callback()
      }
    }
    return {
      index: 0,
      list: [],
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      showVideo: false,
      homeRadio: 'shop',
      goodsRadio: '',
      isService: false,
      isGoods: false,
      colorParams: {
        theme_color: '',
        assistant_theme_color: ''
      },
      basicInfoParams: {
        name: '',
        logo: '',
        index_advertising: '',
        service_tel: ''
      },
      homeSettingParams: {
        is_show: 1,
        index_show: 'shop',
        memu: []
      },
      isNeedServe: true,
      isNeedGoods: true,
      GoodsRadio: 'byGoods',
      serveDisable: false,
      goodsDisable: false,
      goodsSetting: {
        server: { server: 1, is_show: 0, sort: 1 },
        shop: { shop: 1, is_show: 1, sort: 2 }
      },
      videoDisable: true,
      color: '',
      value: '',
      radio: '',
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      rules: {
        theme_color: [
          { required: true, message: '请选择主题色', trigger: 'change' }
        ],
        assistant_theme_color: [
          { required: true, message: '请选择副主题色', trigger: 'change' }
        ],
        name: [{ required: true, message: '请输入平台名称', trigger: 'blur' }],
        // logo: [{ required: true, validator: validateLogo }],
        service_tel: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    isNeedServe(newVal) {
      if (newVal) {
        this.goodsSetting.server.server = 1
        this.serveDisable = false
      } else {
        this.goodsSetting.server.server = 0
        this.serveDisable = true
        this.GoodsRadio = 'byGoods'
        this.isNeedGoods = true
      }
    },
    isNeedGoods(newVal) {
      if (newVal) {
        this.goodsSetting.shop.shop = 1
        this.goodsDisable = false
      } else {
        this.goodsSetting.shop.shop = 0
        this.goodsDisable = true
        this.GoodsRadio = 'byServe'
        this.isNeedServe = true
      }
    },
    GoodsRadio(newVal) {
      if (newVal === 'byGoods') {
        this.goodsSetting.shop.is_show = 1
        this.goodsSetting.server.is_show = 0
      } else if (newVal === 'byServe') {
        this.goodsSetting.shop.is_show = 0
        this.goodsSetting.server.is_show = 1
      }
    },
    showVideo(newVal) {
      const dynamicIndex = this.list.findIndex(item => {
        return item.key === 'dynamic'
      })
      if (newVal) {
        this.videoDisable = false
        this.list[dynamicIndex].is_show = 1
      } else {
        this.videoDisable = true
        this.homeRadio = 'shop'
        this.list[dynamicIndex].is_show = 0
      }
    },
    homeRadio(newVal) {
      const dynamicIndex = this.list.findIndex(item => {
        return item.key === 'dynamic'
      })
      const shopIndex = this.list.findIndex(item => {
        return item.key === 'shop'
      })
      const temp1 = this.list[dynamicIndex]
      const temp2 = this.list[shopIndex]
      if (newVal === 'dynamic') {
        this.list[0] = temp1
        this.list[1] = temp2
      } else {
        this.list[0] = temp2
        this.list[1] = temp1
      }
    }
  },
  created() {
    this._getPlatform()
  },
  methods: {
    logoRemove() {
      this.basicInfoParams.logo = ''
    },
    ...mapMutations('user', ['SET_AVATAR']),
    videoSwitchChange(val) {},
    goodsSettingSubmit() {
      this._setPlatform({ shop_set: this.goodsSetting })
    },
    setIndex(item, name) {
      this.index = item.sort
    },
    unCheckedSuccess(url) {
      this.homeSettingParams.memu[this.index - 1].icon = url
    },
    CheckedSuccess(url) {
      this.homeSettingParams.memu[this.index - 1].icon_on = url
    },
    unCheckedRemove() {
      this.homeSettingParams.memu[this.index - 1].icon = ''
    },
    checkedRemove() {
      this.homeSettingParams.memu[this.index - 1].icon_on = ''
    },
    homeSetting() {
      this.homeSettingParams.memu.forEach((item, index) => {
        item.id = item.sort
      })
      switch (this.showVideo) {
        case false:
          this.homeSettingParams.is_show = 0
          this.homeSettingParams.index_show = 'shop'
          this._setPlatform(this.homeSettingParams)
            .then(() => {
              this._getPlatform()
            })
            .catch(err => {
              console.log(err)
            })
          break
        case true:
          this.homeSettingParams.is_show = 1
          if (this.homeRadio === 'dynamic') {
            this.homeSettingParams.index_show = 'dynamic'
            // const fIndex = this.homeSettingParams.memu.findIndex((item, index) => {
            //   return item.key === 'dynamic'
            // })
            // this.homeSettingParams.memu[fIndex].is_show = 1
          } else {
            this.homeSettingParams.index_show = 'shop'
          }
          this._setPlatform(this.homeSettingParams)
            .then(() => {
              this._getPlatform()
            })
            .catch(err => {
              console.log(err)
            })
      }
    },
    colorSetting() {
      this._setPlatform(this.colorParams)
    },
    basicInfoSetting() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          // 设置logo
          localStorage.setItem('logo', this.basicInfoParams.logo)
          this.SET_AVATAR(this.basicInfoParams.logo)
          if (this.basicInfoParams.logo === '') {
            this.$message({
              message: '请上传logo',
              type: 'warning',
              showClose: true
            })
            return
          }
          this._setPlatform(this.basicInfoParams)
        } else {
          return false
        }
      })
    },
    logoSuccess(url) {
      this.basicInfoParams.logo = url
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAdSuccess(res) {
      if (res.code === ERR_OK) {
        this.basicInfoParams.index_advertising = res.data.file
      }
    },
    // 图片、视频格式化
    handleList(url) {
      const oIndex = url.lastIndexOf('/')
      const name = url.slice(oIndex + 1)
      return { name, url }
    },
    _clearAllImg() {
      switch (this.showVideo) {
        case true:
          for (let i = 1; i <= 10; i++) {
            this.$refs[`upload${i}`].clear()
          }
          break
        case false:
          for (let i = 1; i <= 10; i++) {
            if (i !== 2 && i !== 7) {
              this.$refs[`upload${i}`].clear()
            }
          }
          break
      }
    },
    _setPlatform({
      is_show,
      index_show,
      memu,
      theme_color,
      assistant_theme_color,
      name,
      logo,
      index_advertising,
      service_tel,
      shop_set
    }) {
      return setPlatform({
        is_show,
        index_show,
        memu,
        theme_color,
        assistant_theme_color,
        name,
        logo,
        index_advertising,
        service_tel,
        shop_set
      })
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            this.$message({
              message: res.message,
              type: 'success',
              showClose: true
            })
            return Promise.resolve()
          }
        })
        .catch(err => {
          console.log(err)
          return Promise.reject(err)
        })
    },
    _getPlatform() {
      return new Promise((resolve, reject) => {
        getPlatform()
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res)
              this.homeSettingParams.index_show = res.data.index_show
              this.homeRadio = res.data.index_show
              this.homeSettingParams.memu = JSON.parse(
                JSON.stringify(res.data.memu)
              )
              // console.log(this.homeSettingParams)
              res.data.memu.forEach(item => {
                if (item.key === 'dynamic') {
                  if (item.is_show === 1) {
                    this.showVideo = true
                  } else {
                    this.showVideo = false
                  }
                  item.name = '视频'
                }
              })
              this.list = res.data.memu
              this.colorParams['theme_color'] = res.data.theme_color
              this.colorParams['assistant_theme_color'] =
                res.data.assistant_theme_color
              this.basicInfoParams.name = res.data.name
              this.basicInfoParams.logo = res.data.logo
              this.basicInfoParams.index_advertising =
                res.data.index_advertising
              this.fileList.push(this.handleList(res.data.index_advertising))
              this.basicInfoParams.service_tel = res.data.service_tel
              // 商品设置
              if (res.data.shop_set.shop.shop) {
                this.isNeedGoods = true
              } else {
                this.isNeedGoods = false
              }
              if (res.data.shop_set.server.server) {
                this.isNeedServe = true
              } else {
                this.isNeedServe = false
              }
              if (res.data.shop_set.shop.is_show) {
                this.GoodsRadio = 'byGoods'
              } else {
                this.GoodsRadio = 'byServe'
              }
              this.goodsSetting = res.data.shop_set
            }
            resolve()
          })
          .catch(err => {
            console.log(err)
            reject()
          })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.platform-wrapper {
  box-sizing: border-box;
  background: #fafafa;
  padding-top: 20px;
  box-sizing: border-box;
  .home,
  .goods,
  .theme-color,
  .basic-infor {
    background: #fff;
    .top {
      width: 100%;
      padding: 10px 0;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      border-bottom: 1px solid #eee;
      .title-wrapper {
        display: flex;
        align-content: center;
        .title {
          height: 44px;
          line-height: 44px;
          color: rgba(68, 68, 68, 1);
          font-size: 18px;
          font-family: Roboto;
          font-weight: bold;
          cursor: pointer;
        }
      }
    }
    .content {
      width: 100%;
      padding-left: 40px;
      box-sizing: border-box;
      padding: 30px 30px;
      .el-radio /deep/ .el-radio__inner {
        background: url("./../../assets/choose.png") no-repeat;
        background-size: cover;
        width: 20px;
        height: 20px;
        border-color: #000;
      }
      .el-radio /deep/ .el-radio__input.is-checked .el-radio__inner {
        background: url("./../../assets/choose-active.png") no-repeat;
        background-size: cover;
        border: none;
        &::after {
          opacity: 0;
        }
      }
      .inActive,
      .active {
        padding-left: 138px;
        display: flex;
        align-items: center;
        .upload {
          margin-right: 35px;
        }
        .upload /deep/ .color-red {
          // color: #000;
          // text-align: center;
          // font-size: 14px;
        }
      }
      .active {
      }
    }
  }
  .goods,
  .theme-color,
  .basic-infor {
    margin-top: 15px;
  }
}
.d-flex,
.d-flex-top {
  display: flex;
  align-items: center;
  p {
    margin-right: 10px;
    white-space: nowrap;
  }
  div {
    margin-right: 15px;
    vertical-align: middle;
  }
}
.d-flex-top {
  align-items: flex-start;
  margin: 0;
}
.w-60 {
  width: 180px;
}
.el-color-picker /deep/ .el-color-picker__trigger {
  width: 100px !important;
}
</style>
